/**
 * Created by Joe on 2017/7/5 0005.
 */
var Bill = {
    type: {
        create: 0,
        update: 1,
        readonly: 2
    },
    fields: {
        selects: ["type"], //下拉框
        radios: [],//单选框
        checkboxs: [],//复选款
        textareas: [],//多行文本框
        selfDefine: [{"field": "metroLine ", "selector": "a.metro_line"}]
    },
    submit: 0,


};

$(document).ready(function () {

    initFormValidate();

    $('#DataTables_bill').DataTable({
        "paging": true,
        "searching": true,
        "info": true,
        "ordering": true,
        "language": {
            "url": "../vendor/datatables/zh-cn.json"
        }
    });
    $('#DataTables_mb_bill').DataTable({
        "paging": true,
        "searching": true,
        "info": true,
        "ordering": true,
        "language": {
            "url": "../vendor/datatables/zh-cn.json"
        }
    });
    $('#DataTables_bill_read').DataTable({
        "paging": true,
        "searching": true,
        "info": true,
        "ordering": true,
        "language": {
            "url": "../vendor/datatables/zh-cn.json"
        }
    });
    $('#DataTables_bill_order').DataTable({
        "paging": false,
        "searching": false,
        "info": false,
        "ordering": false,
        "language": {
            "url": "../vendor/datatables/zh-cn.json"
        }
    });
    $('#DataTables_bill_detail_order').DataTable({
        "paging": false,
        "searching": false,
        "info": false,
        "ordering": false,
        "language": {
            "url": "../vendor/datatables/zh-cn.json"
        }
    });
    $('#DataTables_bill_order_received').DataTable({
        "paging": false,
        "searching": false,
        "info": false,
        "ordering": false,
        "language": {
            "url": "../vendor/datatables/zh-cn.json"
        }
    });

    if ($('#datetimepicker').length > 0) {
        $('#datetimepicker').datetimepicker({format: 'yyyy-mm-dd', minView: 2, language: 'zh-CN'});//minView 最精准的时间选择为日期0-分 1-时 2-日 3-月
    }
    if ($('#detailEndDate').length > 0) {
        $('#detailEndDate').datetimepicker({format: 'yyyy-mm-dd', minView: 2, language: 'zh-CN'});
    }
    if ($('#payDatetimepicker').length > 0) {
        $('#payDatetimepicker').datetimepicker({format: 'yyyy-mm-dd', minView: 2, language: 'zh-CN'});
    }
    $('#btn-create-bill').on('click', function () {
        // var companyId = $('#selectCompanyId').val();
        // loadUserByCompanyId(companyId);
        $("#newbill-modal").modal("toggle");
    });
    $('#saveNewBill').on('click', function () {
        requestCreateBill();
    });
    $('#confirmReceived').on('click', function () {
        requestConfirmReceived();
    });
    $('#btn-query-bill').on('click', function () {
        requestQueryBill(Bill.type.create);
    });
    $('#btn-query-readonly').on('click', function () {
        requestQueryBill(Bill.type.readonly);
    });
    $('#DataTables_bill').on('click', '.btn-detail', function () {
        requestAccountBillDetail($(this).siblings("input").val());
    });
    $('#DataTables_bill').on('click', '.btn-confirm', function () {
        requestAccountBillReceived($(this).siblings("input").val());
    });
    $('#DataTables_bill').on('click', '.btn-delete', function () {
        var $tr = $(this).parents('tr');
        var row = $('#DataTables_bill').DataTable().row($tr);
        var url = /*[[@{/accountBill/deleteAccountBill}]]*/ '/accountBill/deleteAccountBill';
        Utils.ajaxSubmit(url + "/" + $(this).siblings("input").val(), {}, function (data) {
            if (data.result == "success") {
                row.remove().draw();
                layer.msg('账单已删除', {time: 3000, icon: 6});
            }
            if (data.result == "fail") {
                Utils.errorAlert(data.result.errorMessage);
            }
        });
    });
    $('.btn-confirm').on('click', function () {
        layer.alert('收款确认成功', {
            skin: 'layui-layer-molv',
            title: '提示信息'
            , closeBtn: 0
            , anim: 4 //动画类型
        });
    });
    /*马币*/
    $('#btn-rewards').on('click', function () {
        $("#rewards-modal").modal("toggle");
    });
    $('#btn-query-mbill').on('click', function () {
        requestQueryMbBill();
    });
    $('#save-new-mbill').on('click', function () {
        if ($("#rewards-mb-form").valid()) {
            requestCreateMbBill();
        }
    });
    $('#selectCompanyId').change(function () {
        // 级联企业下的所有账号
        /* var companyId = $('#selectCompanyId').val();
         loadUserByCompanyId(companyId)*/
        loadBillOrder();
        $("#DataTables_bill_order").DataTable().rows().remove().draw();
    });
    /* $('#userId').change(function () {
     loadBillOrder();
     $("#DataTables_bill_order").DataTable().rows().remove().draw();
     });*/
});
function requestQueryBill(type) {
    $("#DataTables_bill").DataTable().rows().remove().draw();
    var companyId = $("#companyId").val();
    var url = /*[[@{/accountBill/queryAccountBill}]]*/ '/accountBill/queryAccountBill';
    Utils.ajaxSubmit(url + "/" + companyId, {}, function (data) {
        Utils.console_log("data ： ", data);
        if (data.result == "success") {
            addBillRow(data.content, "#DataTables_bill", type);
        }
        if (data.result == "fail") {
            Utils.errorAlert(data.errorMessage);
        }
    });
}
function requestCreateBill() {
    var url = /*[[@{/accountBill/addAccountBill}]]*/ '/accountBill/addAccountBill';
    var params = $("#account-bill-form").serialize();
    Utils.ajaxSubmit(url, params, function (data) {
        if (data.result == "success") {
            $("#newbill-modal").modal("toggle");
            addSingleBillRow(data.content, "#DataTables_bill", Bill.type.create);
        }
        if (data.result == "fail") {
            Utils.errorAlert(data.errorMessage);
        }
    });
}
function requestConfirmReceived() {
    var url = /*[[@{/accountBill/confirmReceived}]]*/ '/accountBill/confirmReceived';
    var params = $("#account-bill-received-form").serialize();
    Utils.ajaxSubmit(url, params, function (data) {
        if (data.result == "success") {
            $("#received-modal").modal("toggle");
            requestQueryBill(Bill.type.create);
        }
        if (data.result == "fail") {
            Utils.errorAlert(data.errorMessage);
        }
    });
}
function loadUserByCompanyId(companyId) {
    $('#userId').empty();
    $("#DataTables_bill_order").DataTable().rows().remove().draw();
    var url = /*[[@{/accountBill/getCompanyInfo}]]*/ '/accountBill/getCompanyInfo';
    Utils.ajaxSubmit(url + "/" + companyId, {}, function (data) {
        if (data.result == 'success') {
            $("#accountUpper").val(data.content.accountUpper);
            fillOptionWithArr("userId", data.content.userList, "")
        }
    });
}
function loadBillOrder() {
    $("#DataTables_bill_order").DataTable().rows().remove().draw();
    var url = /*[[@{/order/findUnSettledOrder}]]*/ '/order/findUnSettledOrder';
    var params = $("#account-bill-form").serialize();
    Utils.ajaxSubmit(url, params, function (data) {
        Utils.console_log("data ： ", data);
        if (data.result == "success") {
            addBillOrder(data.content, "#DataTables_bill_order", 1);
        }
        if (data.result == "fail") {
            Utils.errorAlert(data.errorMessage);
        }
    });
}
function requestAccountBillDetail(accountBillId) {
    $("#DataTables_bill_detail_order").DataTable().rows().remove().draw();
    var url = /*[[@{/accountBill/findDetail}]]*/ '/accountBill/findDetail';
    Utils.ajaxSubmit(url + "/" + accountBillId, {}, function (data) {
        Utils.console_log("data ： ", data);
        if (data.result == "success") {
            $("#detail-modal").modal("toggle");
            Utils.fillForms(data.content, Bill.fields);
            addBillOrder(data.content.orderDtos, "#DataTables_bill_detail_order", 0);
        }
        if (data.result == "fail") {
            Utils.errorAlert(data.errorMessage);
        }
    });
}
function requestAccountBillReceived(accountBillId) {
    $("#DataTables_bill_order_received").DataTable().rows().remove().draw();
    var url = /*[[@{/accountBill/findDetail}]]*/ '/accountBill/findDetail';
    Utils.ajaxSubmit(url + "/" + accountBillId, {}, function (data) {
        Utils.console_log("data ： ", data);
        if (data.result == "success") {
            $("#received-modal").modal("toggle");
            Utils.fillForms(data.content, Bill.fields);
            addBillOrder(data.content.orderDtos, "#DataTables_bill_order_received", 0);
        }
        if (data.result == "fail") {
            Utils.errorAlert(data.errorMessage);
        }
    });
}
function requestQueryMbBill() {
    $("#DataTables_mb_bill").DataTable().rows().remove().draw();
    var companyId = $("#companyId").val();
    var url = /*[[@{/mbBill/queryMb}]]*/ '/mbBill/queryMb';
    Utils.ajaxSubmit(url + "/" + companyId, {}, function (data) {
        Utils.console_log("data ： ", data);
        if (data.result == "success") {
            addMbBillRow(data.content, "#DataTables_mb_bill");
        }
        if (data.result == "fail") {
            Utils.errorAlert(data.errorMessage);
        }
    });
}
function requestCreateMbBill() {
    var url = /*[[@{/mbBill/addAccountMbBill}]]*/ '/mbBill/addAccountMbBill';
    var params = $("#rewards-mb-form").serialize();
    Utils.ajaxSubmit(url, params, function (data) {
        if (data.result == "success") {
            $("#rewards-modal").modal("toggle");
            addSingleMbBillRow(data.content, "#DataTables_mb_bill");
        }
        if (data.result == "fail") {
            Utils.errorAlert(data.errorMessage);
        }
    });
}
/**添加table行*/
function addBillOrder(billOrderList, targetEle, type) {
    $.each(billOrderList, function (k, v) {
        Utils.console_log("v: ", v);
        var checkBoxEle = '';
        if (type == 1) {
            var orderNo = v.orderNo + "-" + v.orderType;
            checkBoxEle = '<input  type="checkbox" name="orderNos" value="' + orderNo + '">';
            $(targetEle).dataTable().fnAddData([checkBoxEle, v.orderNo, v.amount, v.createAtStr]);
        } else {
            $(targetEle).dataTable().fnAddData([v.orderNo, v.orderTypeLabel, v.createAtStr]);
        }

    });
}
/**添加table行*/
function addMbBillRow(mBillList, targetEle) {
    $.each(mBillList, function (k, v) {
        addSingleMbBillRow(v, targetEle);
    });
}
function addSingleMbBillRow(v, targetEle) {
    if (v.orderNo == null) {
        v.orderNo = "";
    }
    $(targetEle).dataTable().fnAddData([v.amount, v.markLabel, v.typeLabel, v.orderNo, v.createAtStr, v.memo]);
}
/**添加table行*/
function addBillRow(billList, targetEle, type) {
    $.each(billList, function (k, v) {
        Utils.console_log("addBillRow each v: ", v)
        addSingleBillRow(v, targetEle, type);
    });
}
function addSingleBillRow(v, targetEle, type) {
    v.orderNos = v.orderNos ? v.orderNos[0] + "..." : "";
    var btnGroupEle = '<input type="hidden" value="' + v.id + '"> <a class="btn btn-primary btn-detail" >查看明细</a>';
    if (Bill.type.create == type) {
        if (v.payStatus !== '1' && v.payStatus !== '3') {
            btnGroupEle = btnGroupEle.concat('&nbsp;&nbsp;&nbsp;<a class="btn btn-primary btn-confirm">确认收款</a>');
        }
        btnGroupEle = btnGroupEle.concat('&nbsp;&nbsp;&nbsp;<a class="btn btn-danger btn-delete">删除</a>');
    }
    $(targetEle).dataTable().fnAddData([v.accountBillNo, v.amount, v.orderNos, v.payStatusLabel, v.beginDateStr, v.endDateStr, btnGroupEle]);
}

function fillOptionWithArr(el_id, array, selected_code) {
    var el = $('#' + el_id);
    el.empty();
    if (array) {
        var index = 1;
        var selected_index = 0;
        if (array.length == 1) {
            el.append('<option value="">请选择</option>');
        }
        $.each(array, function (k, v) {
            var code = v.code;
            var option = '<option value="' + v.id + '">' + v.realName + "-" + v.userName + '</option>';
            /*     if (k == 1) {
             option = '<option value="' + v.id + '" selected >' + v.realName + "-" + v.userName + '</option>';
             }
             if (code == selected_code) {
             option = '<option value="' + v.id + '" selected >' + v.realName + "-" + v.userName + '</option>';
             }*/
            el.append(option);
            if (code == selected_code) {
                selected_index = index;
            }
            index++;
        });
        el.attr('selectedIndex', selected_index);
    }
}

function initFormValidate() {
    if($("#rewards-mb-form").length>0){
        var validator = $("#rewards-mb-form").validate({
            errorElement: "span",
            errorClass: "error-block",
            focusInvalid: true,
            rules: {
                amount: {required: true},
                memo: {required: true, maxlength: 255}
            },
            messages: {
                amount: {required: "请填写马币金额"},
                memo: {required: "请填写补充说明", maxlength: $.validator.format("长度不能超过{0}")}
            }
        });
    }
}